package com.hzwq.demo2.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzwq.demo2.role.entity.Role;
import com.hzwq.demo2.role.service.IRoleService;
import com.hzwq.demo2.user.entity.User;
import com.hzwq.demo2.user.mapper.UserMapper;
import com.hzwq.demo2.userrole.entity.UserRole;
import com.hzwq.demo2.userrole.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @since 2020-08-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    IRoleService roleService;
    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    UserMapper userMapper;

    @Override
    public User getById(Serializable id) {
        User user = super.getById(id);
        List<Role> roleList = roleService.listByUserId((Integer) id);
        user.setRoleList(roleList);
        return user;
    }

    @Override
    @Transactional
    public void saveUserAndRole(User user) {
        if (user.getId() != null) {
            user.setUpdateTime(new Date());
        } else {
            user.setInsertTime(new Date());
        }
        super.saveOrUpdate(user);

        // 前台所选角色信息
        List<Role> roleList = user.getRoleList();
        if(roleList!=null) {
            System.out.println(user.toString());
            // 存放需要保存的用户角色关联数据
            List<UserRole> userRoleList = new ArrayList<UserRole>();
            // 删除用户之前关联的所有角色
            QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
            wrapper.eq("user_id", user.getId());
            userRoleService.remove(wrapper);
            // 循环前台所选角色信息，生成用户角色关联数据并保存
            for (Role role : roleList) {
                if (role != null && role.getId() != null) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(role.getId());
                    userRoleList.add(userRole);
                }
            }
            // 保存用户角色关联信息
            userRoleService.saveBatch(userRoleList);
        }
    }

    @Override
    public void delById(Integer id) {
        if (id!=null){
            int i = userMapper.delById(id);
            System.out.println(i);
            if (i==1){
                System.out.println("假删除成功！");
            }
        }
    }
}
